﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class UIManager{
    /**
     * 存储所有面板的路径
     */
    private Dictionary<UIPanelType, string> panelPathDict;//保存所有实例化面板的Prefab路径
	private Dictionary<UIPanelType,BasePanel> panelDict;//保存所有面板的实例化对象
    private Stack<BasePanel> panelStack;


    private static UIManager _instance = null;
    private Transform canvasTransform;
    public Transform CanvasTransform {
        get {
            if (canvasTransform == null) {
                canvasTransform = GameObject.Find("Canvas").transform;
            }
            return canvasTransform;
        }
    }
   
    /**
     * 单例唯一获得方法
     */
    public static UIManager Instance {
        get {

            if (_instance == null)
            {
                _instance = new UIManager();
            }
            return _instance;
        }
    }


	private BasePanel GetPanel(UIPanelType panelType)
	{
		if (panelDict == null) {
			panelDict = new Dictionary<UIPanelType, BasePanel>();
		}
        BasePanel panel = panelDict.TryGet(panelType);
        if (panel == null)
        {
            string path = panelPathDict.TryGet(panelType);
            GameObject instancePanel = GameObject.Instantiate(Resources.Load<GameObject>(path));
            instancePanel.transform.SetParent(CanvasTransform,false);
            panelDict.Add(panelType, instancePanel.GetComponent<BasePanel>());
            return instancePanel.GetComponent<BasePanel>();
        }
        else
        {
            return panel;
        }
	}

    private UIManager() {
        ParseUIPanelTypeJson();
    }

    private void ParseUIPanelTypeJson()
    {
        panelPathDict = new Dictionary<UIPanelType, string>();
        TextAsset textAsset = Resources.Load<TextAsset>("UIPanelType");
        UIPanelTypeJson panelJson = JsonUtility.FromJson<UIPanelTypeJson>(textAsset.text);
      
        foreach (UIPanelInfo info in panelJson.panelInfoList)
        {
            Debug.Log(info.path);
            panelPathDict.Add(info.panelType, info.path);
        }
    }


    /**
     * 
     * 显示页面
     */
    public void PushPanel(UIPanelType panelType)
    {
        if (panelStack == null)
        {
            panelStack = new Stack<BasePanel>();
        }

		if (panelStack.Count > 0) {
			BasePanel topPanel = panelStack.Peek ();
			topPanel.OnPause();
		}

        BasePanel panel = GetPanel(panelType);
		panel.OnEnter ();
        panelStack.Push(panel);
    }

    /**
     * 页面出栈
     */
    public void popPanel() {
		if (panelStack == null) 
		{
			panelStack = new Stack<BasePanel> ();
		}

		if(panelStack.Count <=  0)return;

		BasePanel topPanel = panelStack.Pop ();
		topPanel.OnExit ();
	
		if (panelStack.Count <= 0)
			return;
		BasePanel topPanel2 = panelStack.Peek ();
		topPanel2.OnResume ();
    }

    public void Test() {
        string path;
        panelPathDict.TryGetValue(UIPanelType.Knaspack, out path);
        Debug.Log(path);
    }
}
